// pages/toolPages/videoModify/videoModify.js
let interstitialAd = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
      rawVidMd5: '',
      rawVidSize: '',
      rawVidDuration: '',
      rawVidFPS: '',
      rawVidBitrate: '',
      rawVidHeight: '',
      rawVidWidth: '',
      rawVidUrl: '',
      newVidMd5: '',
      newVidSize: '',
      newVidDuration: '',
      newVidFPS: '',
      newVidBitrate: '',
      newVidHeight: '',
      newVidWidth: '',
      newVidUrl: '',
      newVidResolution: 1,

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      if(wx.createInterstitialAd){
        interstitialAd = wx.createInterstitialAd({ adUnitId: 'adunit-c04c8689d165224f' })
        interstitialAd.onLoad(() => {
          console.log('onLoad event emit')
        })
        interstitialAd.onError((err) => {
          console.log('onError event emit', err)
        })
        interstitialAd.onClose((res) => {
          console.log('onClose event emit', res)
        })
      }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        // 超过70秒可以显示插屏广告
        var currentTime = new Date();
        var lastTime = wx.getStorageSync('cpShowTime')
        var interval = (currentTime.getTime() -lastTime.getTime()) /1000;
        console.log("==间隔： "+interval)
        if (interval>70){
          wx.setStorageSync('cpShowTime', currentTime)
          interstitialAd.show().catch((err) => {
            console.error(err)
            wx.setStorageSync('cpShowTime', lastTime)
          })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    getVidMd5: function(filePath, param){
      wx.showLoading({
        title: '正在计算MD5',
      })
      const fs = wx.getFileSystemManager()
      var ts = this;
      wx.getVideoInfo({
        src: filePath,
        success(res){

              // 修改展示数据
              if(param == 'rowVid'){
                ts.setData({
                  rawVidSize: (res.size/1024).toFixed(4),
                  rawVidDuration: res.duration,
                  rawVidFPS: res.fps,
                  rawVidWidth: res.width,
                  rawVidHeight: res.height,
                  rawVidBitrate: res.bitrate,
                })
              }else{
                ts.setData({
                  newVidSize: res.size,
                  newVidDuration: res.duration,
                  newVidFPS: res.fps,
                  newVidWidth: res.width,
                  newVidHeight: res.height,
                  newVidBitrate: res.bitrate,
                  newVidUrl: filePath,
                })
              }
              const ab = new ArrayBuffer((res.size+1)*1024)
              fs.open({
                  filePath: filePath,
                  flag: 'r',
                  success(res) {
                    // 读取文件到 ArrayBuffer 中
                    fs.read({
                      fd: res.fd,
                      arrayBuffer: ab,
                      length: ab.byteLength,
                      success(res) {
                        var MD5 = require('../../../utils/md5.js');
                        let spark = new MD5.ArrayBuffer();
                        spark.append(res.arrayBuffer.slice(0,res.bytesRead));
                        var md5String = spark.end(false);
                        if (param == 'rowVid'){
                          ts.setData({
                            rawVidMd5: md5String,
                          })
                        }else{
                          ts.setData({
                            newVidMd5: md5String,
                          })
                        }
                        wx.hideLoading()
                      },
                      fail(res){
                          if (param == 'rowVid'){
                            ts.setData({
                              rawVidMd5: '视频过大，计算失败',
                            })
                          }else{
                            ts.setData({
                              newVidMd5: "视频过大，计算失败，但已经修改",
                            })
                          }
                          wx.hideLoading()
                          console.log(res);
                      }
                    })
                  },
                  fail(res){
                      wx.hideLoading()
                      console.log(res)
                      if (param == 'rowVid'){
                        ts.setData({
                          rawVidMd5: '视频过大，计算失败',
                        })
                      }else{
                        ts.setData({
                          newVidMd5: "视频过大，计算失败，但已经修改",
                        })
                      }
                  }
                })
        },
        fail(res){
              wx.hideLoading()
            console.log(res);
            if (param == 'rowVid'){
              ts.setData({
                rawVidMd5: '视频过大，计算失败',
              })
            }else{
              ts.setData({
                newVidMd5: "视频过大，计算失败，但已经修改",
              })
            }
        },
      })
  },
  upLoadVid: function(){
    var ts = this;
    ts.setData({  rawVidMd5: '',
                  rawVidSize: '',
                  rawVidDuration: '',
                  rawVidFPS: '',
                  rawVidBitrate: '',
                  rawVidHeight: '',
                  rawVidWidth: '',
                  rawVidUrl: '',
                  newVidMd5: '',
                  newVidSize: '',
                  newVidDuration: '',
                  newVidFPS: '',
                  newVidBitrate: '',
                  newVidHeight: '',
                  newVidWidth: '',
                  newVidResolution: 1,
                  newVidUrl: '',})
    wx.chooseMedia({
        count: 1,
        mediaType: ['video'],
        sourceType: ['album'],
        sizeType:['original'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
            ts.setData({
              rawVidUrl: res.tempFiles[0].tempFilePath,
            });
            ts.getVidMd5(res.tempFiles[0].tempFilePath, "rowVid");
        },
        fail(res){
            wx.showModal({
              title: '上传失败',
              content: '请重新上传，如持续不能上传，请至用户页联系客服',
              complete: (res) => {
                if (res.cancel) {
                }
                if (res.confirm) {
                }
              }
            })
        },
    })
  },
  changeFPS(e){
    this.setData({
      newVidFPS: e.detail.value,
    })
  },
  changeBitrate(e){
    this.setData({
      newVidBitrate: e.detail.value,
    })
  },
  changeResolution(e){
    this.setData({
      newVidResolution: e.detail.value,
    })
  },
  modifyVid: function(){
    var ts = this;
    // 校验参数
    if(ts.data.rawVidUrl == ""){
      wx.showToast({
        icon: 'error',
        title: '请上传原视频',
      })
      return;
    }
    if(ts.data.newVidFPS == '' || ts.data.newVidFPS>ts.data.rawVidFPS){
      wx.showToast({
        icon: 'error',
        title: 'FPS不合法',
      })
      return;
    }
    if(ts.data.newVidBitrate == '' || ts.data.newVidBitrate>=ts.data.rawVidBitrate){
      wx.showToast({
        icon: 'error',
        title: '码率不合法',
      })
      return;
    }
    if(ts.data.newVidResolution>1 || ts.data.newVidResolution <= 0){
      wx.showToast({
        icon: 'error',
        title: '分辨率不合法',
      })
      return;
    }

    wx.showLoading({
      title: '正在修改MD5',
    })
    wx.compressVideo({
      bitrate: ts.data.newVidBitrate,
      fps: ts.data.newVidFPS,
      resolution: ts.data.newVidResolution,
      src: ts.data.rawVidUrl,
      success(res){
        wx.hideLoading()
        ts.getVidMd5(res.tempFilePath, 'newVid')
      },
      fail(res){
        wx.hideLoading();
        console.log(res);
        wx.showModal({
          title: '修改失败',
          content: '请重试或者联系客服',
          complete: (res) => {
            if (res.cancel) {
            }
            if (res.confirm) {
            }
          }
        })
      }
    })
  },
  downloadVid: function(){
    var ts = this;
    if (ts.data.newVidUrl == ""){
      wx.showToast({
        icon: 'error',
        title: '请先修改MD5',
      })
        return
    }else{
        wx.showLoading({
          title: "正在下载",
        })
        wx.saveVideoToPhotosAlbum({
            filePath: ts.data.newVidUrl,
            success(res){
                wx.hideLoading()
                wx.showToast({
                  title: '视频下载成功',
                  icon: 'success',
                  duration: 2500,
                })
            },
            fail(res){
                wx.hideLoading()
                console.log(res.errMsg)
                wx.showModal({
                  title: '下载失败请重试',
                  content: res.errMsg,
                  complete: (res) => {
                    if (res.cancel) {
                    }
                
                    if (res.confirm) {
                    }
                  }
                })
            }
          })
    }
},
adLoadB() {
  console.log('MD5页面底部小程序视频广告加载成功')
},
adErrorB(err) {
  console.log('MD5页面底部小程序视频广告加载失败', err)
},
adCloseB() {
  console.log('MD5页面底部小程序视频广告关闭')
},
})